﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Road3App.ViewModels;

namespace Road3App.Views.UserControls.EditControls.Crossroad
{
    /// <summary>
    /// Interaction logic for EditCellStatesCrossRoadUC.xaml
    /// </summary>
    public partial class EditGridUC : UserControl
    {
        private string _param;
        private CrossroadViewModel _viewModel;

        public EditGridUC()
        {
            InitializeComponent();
            this.DataContextChanged += EditCellStatesCrossRoadUC_DataContextChanged;
        }
        
        private void EditCellStatesCrossRoadUC_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            _viewModel = this.DataContext as CrossroadViewModel;
            if (_viewModel == null)
                return;

            _param = _viewModel.Param;

            if (_param == "cell")
                CellGrid.ItemsSource = _viewModel.CellCollection;
            else if (_param == "trafficlight")
                CellGrid.ItemsSource = _viewModel.TrafficLightCollection;

            _viewModel.GridChanged += _viewModel_GridChanged;
            _viewModel.OnGridChanged();
        }

        private void _viewModel_GridChanged(object sender, EventArgs e)
        {
            var grid = FindVisualChild<Grid>(CellGrid);
            if (grid == null)
                return;

            grid.RowDefinitions.Clear();
            grid.ColumnDefinitions.Clear();

            for (int i = 0; i < _viewModel.heigth + 2; i++)
                grid.RowDefinitions.Add(new RowDefinition());
            for (int i = 0; i < _viewModel.width + 2; i++)
                grid.ColumnDefinitions.Add(new ColumnDefinition());
        }

        private TChildItem FindVisualChild<TChildItem>(DependencyObject obj) where TChildItem : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                var child = VisualTreeHelper.GetChild(obj, i);

                if (child != null && child is TChildItem)
                    return (TChildItem)child;

                var childOfChild = FindVisualChild<TChildItem>(child);

                if (childOfChild != null)
                    return childOfChild;
            }

            return null;
        }

        private void CellGrid_Loaded(object sender, RoutedEventArgs e)
        {
            _viewModel.OnGridChanged();
        }
    }
}
